//
//  ByNetBaseError.m
//  jmsfhz_ios
//
//  Created by pro on 16/8/10.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ByNetBaseError.h"

@implementation ByNetBaseError

- (id)initWithError:(NSError *)error {
    if (self = [super init]) {
        
        self.error = error;
    }
    
    return self;
}

- (void)errorAnalysis {
    
    NSError *error = self.error;
    DLog(@"%@", error);
    if ([self failureProcess:error]) {
        NSString *desc = [self failureProcess:error];
        self.failourBlock(desc, error.code);
    } else {
        NSError *underError = [error.userInfo objectForKey:@"NSUnderlyingError"];
        NSString *desc = nil;
        if(underError != nil){
            
            NSData *inlineData = [underError.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"];
            
            desc = [[NSString alloc] initWithData:inlineData encoding:NSUTF8StringEncoding];
            
            if ([desc isStringNull]) {
                desc = @"网络不好，请检查";
            }
            if ([desc containsString:@"<!DOCTYPE"] || [desc containsString:@"<html>"]) {
                desc = @"服务器返回异常!";
            }
        } else {
            
            NSData *inlineData = [error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"];
            
            if(inlineData) {
                desc = @"服务器开小差了!请重试";
            } else {
                desc = @"未知错误";
            }
        }
        
        self.failourBlock(desc, underError.code);
    }
    
}


- (NSString *)failureProcess:(NSError * )error {
    
    if (error.code == NSURLErrorTimedOut) {
        return @"请求超时!";
    }
    if(error.code == NSURLErrorBadURL) {
        return @"非法请求地址!";
    }
    if(error.code == NSURLErrorCannotFindHost) {
        return @"无法查找远程主机!";
    }
    if(error.code == NSURLErrorCannotConnectToHost) {
        return @"远程主机无法连接!";
    }
    if([error.domain isEqualToString: @"NSURLErrorDomain"]) {
        return @"请求失败,请重试!";
    }
    
    return nil;
}
@end
